//
// Created by CodeZijun on 2022/12/3.
//

#include "Forest.h"
//层序建树
void tree::produceTree() {
    string tmp;
    cin>>tmp;
    if(tmp=="$"||tmp=="%")
        return;
    else{
        root = new treeNode;
        root->data = tmp;
    }
    queue<treeNode*> q;
    q.push(root);
    while(!q.empty()){
        cin>>tmp;
        if(tmp=="$")
            break;
        else{
            if(tmp=="%"){
                q.pop();
                continue;
            }
            else{
                treeNode* p = new treeNode;
                p->data = tmp;
                q.front()->myChild.push_back(p);
                q.push(p);
            }
        }
    }
}

//先根遍历
void tree::preOrder(treeNode* p) {
    if(!p) return;
    else{
        cout<<p->data<<" ";
        for(int i=0;i<p->myChild.size();i++)
            preOrder(p->myChild[i]);
    }
}

//后根遍历
void tree::aftOrder(treeNode *p) {
    if(!p) return;
    else{
        for(int i=0;i<p->myChild.size();i++)
            aftOrder(p->myChild[i]);
        cout<<p->data<<" ";
    }
}

//访问树的棵树
int Forest::treeNum() {
    return frt.size();
}

//加树
void Forest::addTree(tree *t) {
    frt.push_back(t);
}

//访问指定树
tree* Forest::visitTree(int n) {
    return frt[n-1];
}

//森林前序遍历
void Forest::preOrder() {
    for(int i=0;i<frt.size();i++)
        frt[i]->preOrder(frt[i]->root);

}

//森林后序遍历
void Forest::aftOrder() {
    for(int i=0;i<frt.size();i++)
        frt[i]->aftOrder(frt[i]->root);
}

//树转换树为二叉树
binTreeNode* tree::revBinTree(treeNode* p) {
    binTreeNode* btn = new binTreeNode;
    btn->data = p->data;
    if(p->myChild.empty())
        return btn;
    else{
        btn->l_child = revBinTree(p->myChild[0]);
        binTreeNode* tmp = btn->l_child;
        for(int i=1;i<p->myChild.size();i++){
            tmp->r_child = revBinTree(p->myChild[i]);
            tmp = tmp->r_child;
        }
        return btn;
    }
}

//森林转换为二叉树
binTreeNode* Forest::revBinTree() {
    binTreeNode* ans = frt[0]->revBinTree(frt[0]->root);
    binTreeNode* tmp = ans;
    for(int i=1;i<frt.size();i++){
        tmp->r_child = frt[i]->revBinTree(frt[i]->root);
        tmp = tmp->r_child;
    }
    return ans;
}
